#include <iostream>
#include <vector>
#include "DateRange.h"

void overlaps(const DateRange& dr1,const DateRange& dr2, DateRange *& overlap) {
  overlap = new DateRange(-1,-1);
  if(dr1.get_start() <= dr2.get_start() && dr2.get_start() <= dr1.get_end()) {
    if(dr1.get_end() <= dr2.get_end()) {
      overlap->set_start(dr2.get_start());
      overlap->set_end(dr1.get_end());
    }
    else {
      overlap->set_start(dr2.get_start());
      overlap->set_end(dr2.get_end());
    }
  }
  else if(dr2.get_start()<=dr1.get_start() && dr1.get_start()<=dr2.get_end()) {
    if(dr2.get_end() <= dr1.get_end()) {
      overlap->set_start(dr1.get_start());
      overlap->set_end(dr2.get_end());
    }
    else {
      overlap->set_start(dr1.get_start());
      overlap->set_end(dr2.get_end());
    }
  }
  else {
    overlap->set_start(-1);
    overlap->set_end(-1);
  }
}

void intersect(const std::vector<int>& numbers, const std::vector<DateRange*> ranges, std::vector<int> &intersection ){
  long i=0;
  long j=0;
  
  while(numbers.size() > i && ranges.size() > j) {
    try {  
      if(numbers.at(i) >= ranges.at(j)->get_start() && numbers.at(i) <= ranges.at(j)->get_end()) {
	// intersects
	intersection.push_back(numbers.at(i));
	i++;
      } else if(numbers.at(i) > ranges.at(j)->get_end()) {
	// number is on right of the range
	j++;
      } else {
	i++;
      }
    }catch (...) {
      std:: cout << "Exceeds vector dimensions." <<std:: endl;
    }
  }
}

int main(){

  DateRange* dr1 = new DateRange(3,5);
  DateRange* dr2 = new DateRange(4,9);
  DateRange* dr3 = new DateRange(6,9);
  DateRange* dr4 = new DateRange(8,11);
  DateRange* dr5 = new DateRange(13,15);
  DateRange* dr6 = new DateRange(15,17);
  
  std::cout<<"abuzittin"<<std::endl;
  
  DateRange* o_range;  
  overlaps(*dr3,*dr2,o_range);
  std::cout << o_range->get_start() << " - " << o_range->get_end() << std::endl;
  
  std::vector<int> numbers;
  std::vector<DateRange*> ranges;
  std::vector<int> intersection;

  numbers.push_back(2);
  numbers.push_back(7);
  numbers.push_back(15);
  numbers.push_back(17);
  numbers.push_back(20);

  ranges.push_back(dr1);
  ranges.push_back(dr2);
  ranges.push_back(dr3);
  ranges.push_back(dr4);
  ranges.push_back(dr5);
  ranges.push_back(dr6);

  intersect(numbers, ranges, intersection);
  std::cout << "size of intersect: " << intersection.size() << std::endl;
  for(long iterator=0; iterator < intersection.size(); iterator++) {
    std::cout << intersection.at(iterator)<< std::endl;
  }
  delete o_range;
  delete dr1;
  delete dr2;
  delete dr3;
  delete dr4;
  delete dr5;
  delete dr6;

  return 0;
}
